package com.codejoys.monitor.web;

import com.codejoys.monitor.dto.BaseResult;
import com.codejoys.monitor.dto.DeviceDto;
import com.codejoys.monitor.dto.SystemStatus;
import com.codejoys.monitor.event.LogStatusEvent;
import com.codejoys.monitor.service.DeviceService;
import com.codejoys.monitor.service.ModbusService;
import com.codejoys.monitor.service.StatusService;
import com.fasterxml.jackson.databind.ser.Serializers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class StatusController {
    private static final Logger logger = LoggerFactory.getLogger(StatusController.class);

    @Autowired
    StatusService statusService;

    @Autowired
    ModbusService modbusService;

    // 检查系统状态，包括CAN设备连通性，modbus连通性
    @GetMapping("/status/system")
    public BaseResult checkSystemStatus() {
        SystemStatus status = modbusService.checkSystemStatus();

        return BaseResult.builder()
                .success()
                .data(status)
                .build();
    }

    @GetMapping("/status/start")
    public BaseResult start(DeviceDto device) {
        statusService.start(device);

        return BaseResult.success();
    }

    @GetMapping("/status/stop")
    public BaseResult stop(DeviceDto device) {
        // 手动停机，需要备注错误
        device.setNeedRemark((byte) 1);
        device.setAgingResult((byte) 2);
        statusService.close(device);

        return BaseResult.success();
    }

    // 移除设备
    @GetMapping("/status/remove")
    public BaseResult remove(DeviceDto device) {
        statusService.remove(device);

        return BaseResult.success();
    }

    // 重置设备（设备在老化出错的情况下，可以不与通道解绑，直接重置成已扫码的初始状态）
    @GetMapping("/status/restore")
    public BaseResult restore(DeviceDto device) {
        statusService.restore(device);

        return BaseResult.success();
    }

    // 扫码批量解绑设备
    @PostMapping("/status/batchDetach")
    public BaseResult batchDetach(@RequestBody List<DeviceDto> devices) {
        statusService.batchDetach(devices);

        return BaseResult.success();
    }

    @PostMapping("/status/startAll")
    public BaseResult startAll(@RequestBody List<DeviceDto> devices) {
        logger.debug("devices: {}", devices);

        statusService.startAll(devices);

        return BaseResult.success();
    }

    @PostMapping("/status/stopAll")
    public BaseResult stopAll(@RequestBody List<DeviceDto> devices) {
        statusService.stopAll(devices);

        return BaseResult.success();
    }

//    @GetMapping("/status")
//    public BaseResult getStatus(DeviceDto deviceDto) {
//        int status = statusService.getStatus(deviceDto);
//
//        return BaseResult.builder().data(status).success().build();
//    }

    @GetMapping("/status/alert")
    public BaseResult alert(DeviceDto device) {
        statusService.sendAlert(device);

        return BaseResult.success();
    }

    @PostMapping("/status/channels")
    public BaseResult channelStatus(@RequestBody String[] channels) {
        logger.info("channels {}", Arrays.stream(channels).collect(Collectors.toList()));

        List<DeviceDto> devices = statusService.getChannelStatus(channels);

        return BaseResult
                .builder()
                .data(devices)
                .success()
                .build();
    }

    @Autowired
    ApplicationContext context;

    @GetMapping("/status/logdown")
    public BaseResult logStatus(@RequestParam("on") boolean on) {
        context.publishEvent(new LogStatusEvent(this, on));
        return BaseResult.success();
    }

    @GetMapping("/status/stopAlarm")
    public BaseResult stopAlarm() {
        modbusService.stopAlarm();

        return BaseResult.success();
    }

    // 查询各老化房温度
    @GetMapping("/status/getTprs")
    public BaseResult getTemperatures(
            @RequestParam("cabinet") String cabinet) {      // 机柜    A03X, A03Y, A04X, A04Y

        List<String> tprs = modbusService.getTemperatures(cabinet);

        return BaseResult
                .builder()
                .data(tprs)
                .success()
                .build();
    }

    // 查询各机柜电源开关状态
    @GetMapping("/status/getPowerState")
    public BaseResult getPowerState(
            @RequestParam("cabinet") String cabinet) {      // 机柜    A03X, A03Y, A04X, A04Y

        final List<Boolean> states = modbusService.readPowerState(cabinet);
        // final List<Boolean> states = createDummyState();
        return BaseResult
                .builder()
                .data(states)
                .success()
                .build();
    }

    /*
    private static List<Boolean> createDummyState() {
        byte[] resultData = {
                0x00, 0x00, 0x00, 0x00,
                0x00, 0x06, 0x01, 0x02,
                0x03, 0x54, (byte) 0xAB, 0x02
        };

        boolean[] marks = new boolean[18];
        for (int i = 0; i < 8; i++) {
            int mask = 0x1 << i;
            marks[i] = ((resultData[9] & mask) == mask);        // 相等表示闭合
            marks[i + 8] = ((resultData[10] & mask) == mask);
        }

        marks[16] = ((resultData[11] & 0x01) == 0x01);
        marks[17] = ((resultData[11] & 0x02) == 0x02);

        logger.info("开关结果：\n{}", marks);

        List<Boolean> result = new ArrayList<>();
        for (boolean m : marks) {
            result.add(m);
        }
        return result;
    }
    */
}
